<?php
/**
 * *** BEGIN LICENSE BLOCK *****
 *
 * This file is part of phpSearch (http://www.elgatonaranja.com/).
 *
 * Software License Agreement (New BSD License)
 *
 * Copyright (c) 2006-2009, Christoph Dorn
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *
 *     * Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *
 *     * Neither the name of Christoph Dorn nor the names of its
 *       contributors may be used to endorse or promote products derived from this
 *       software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK *****
 *
 * @copyright   Copyright (C) 2011 Jordi Enguídanos
 * @author      Jordi Enguídanos <jordifreek@gmail.com>
 * @license     http://www.opensource.org/licenses/bsd-license.php
 * @package     phpSearch
 */


/**
 * csvSearch
 *
 * Este archivo es un módulo de phpSearch
 * Realiza busquedas de texto en archivos CSV utilizando el motor de phpSearch
 *
 * @package phpSearch
 * @author Jordi Enguídanos <jordifreek@gmail.com>
 * @copyright 2011
 * @version 0.1beta
 * @access public
 */
class csvSearch extends phpSearch
{
    public $csv_file = '';
    public $delimiter = ',';

    public function __construct(){}

    /**
     * csvSearch::q()
     *
     * Carga un archivo CSV y realiza la busqueda de $keywords en las columnas indicadas en $fields
     *
     * @param string $csv_file Ruta al archivo csv
     * @param string $keywords Palabras clave de busqueda, puede ser una palabra o una frase
     * @param string $fields Campos/columnas de archivo CSV donde se buscará. Separadas por comas
     * @return bool|int Si hay resultados devuelve el numero de resultados, si no devuelve false
     */
    public function q( $csv_file, $keywords, $fields='*' )
    {
        if ( file_exists($csv_file) and is_readable($csv_file) )
        {
            $row = 0;
            $num_rows = 0;
            $csv_columns = array();
            if ( ($h = fopen( $csv_file, "r" )) !== false )
            {
                while ( ($data = fgetcsv($h, 1000, $this->delimiter) ) !== false)
                {
                    if ( $row == 0 )
                    {
                        // en la primera fila establecemos los campos que componen el csv
                        $num_rows    = count($data);
                        $csv_columns = $data;

                    }else
                    {
                        $ouhyeah = array();

                        // Todas las filas deben tener el mismo número de campos.
                        // De no ser así entendemos que el archivo CSV está mal formado.
                        if ($num_rows == count($data))
                        {
                            for ($c=0; $c < $num_rows; $c++) {
                                $ouhyeah[$csv_columns[$c]] = $data[$c];
                            }
                        }else
                        {
                            // esta fila no contiene las mismas columnas que la fila 1
                            $this->warn[] = 'La fila '.$row.' no contiene las mismas columnas que la fila 0';
                        }


                        // si se ha encontrado algo
                        if ( count($ouhyeah) )
                        {
                            // lo enviamos a search())
                            $this->search($ouhyeah, $keywords, $fields);
                        }
                    }

                    $row++;
                }
                fclose($h);

                // Devolvemos el numero de resultados y hacemos que el array $result
                // esté disponible con los resultados ordenados por relevancia.
                return $this->get_result();
            }
        }else
        {
            $this->error[] = 'No se ha encontrado el archivo '.$csv_file.' o no tiene permisos de lectura';
        }

        return false;
    }
}

?>